# -*- coding: utf-8 -*-
import re

from datetime import datetime
from flask import g
from flask import jsonify, abort, request, url_for

from .. import db
from ..models import Job, Star
from .authentication import auth
from . import api


@api.route('/jobs/')
@auth.login_required
def get_jobs():
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('s', '', type=unicode)
    print keyword
    job_query = Job.query
    if keyword:
        job_query = job_query.whoosh_search(keyword)
    pagination = job_query.paginate(
        page, per_page=20, error_out=False)
    jobs = pagination.items
    prev = None

    args = {}
    for k in request.args:
        args[k] = request.args[k]
    args['_external'] = True
    if pagination.has_prev:
        args['page'] = page - 1 ;
        prev = url_for('api.get_jobs', **args)
    next = None
    if pagination.has_next:
        args['page'] = page + 1 ;
        next = url_for('api.get_jobs', **args)

    return jsonify({
        'jobs': [job.to_json() for job in jobs],
        'prev': prev,
        'next': next,
        'count': pagination.total
    })


@api.route('/job/<int:id>')
@auth.login_required
def get_job(id):
    job = Job.query.get_or_404(id)
    return jsonify(job.to_json())


@api.route('/job/star/<int:id>')
@auth.login_required
def star_job(id):
    star = Star.query.filter_by(user_id=g.current_user.id, job_id=id).first()

    if star is not None:
        abort(400)

    star = Star(
        user_id=g.current_user.id,
        job_id=id
    )

    db.session.add(star)
    db.session.commit()
    return jsonify({"message": u"关注成功！", "error": "0"})


@api.route('/job/unstar/<int:id>')
@auth.login_required
def unstar_job(id):
    star = Star.query.filter_by(user_id=g.current_user.id, job_id=id).first()

    if star is None:
        abort(404)

    db.session.delete(star)
    db.session.commit()
    return jsonify({"message": u"取消关注成功！", "error": "0"})


@api.route('/job/<int:id>/alarm/<time>/')
@auth.login_required
def alarm_job(id, time):
    star = Star.query.filter_by(user_id=g.current_user.id, job_id=id).first()

    if star is None:
        abort(404)

    if time == "-1":
        star.alarm = None
        msg = u'取消提醒成功。'
    elif re.match(r'(\d{4})-(0?\d{1}|1[0-2])-(0?\d{1}|[12]\d{1}|3[01]) '
                      r'(0?\d{1}|1\d{1}|2[0-3]):(0?\d{1}|[1-5]\d{1})$', time):
        star.alarm = time
        msg = u'设置提醒成功。'
    else:
        msg = u'时间格式错误。'
    print time, id

    db.session.add(star)
    db.session.commit()
    return jsonify({"message": msg, 'error': "0"})

